#!/bin/bash

# Usage:
#   default mode: echo "$var" | fs::write $file_path
#   append mode: echo "$var" | fs::write -a $file_path
#
# Example:
#   echo "hi" | fs::write /tmp/hi
#   echo "$HOME" | fs::write /tmp/hi
#
#   @NOTICE 当写入多行数据的时候，必须加引号，否则换行将消失
#     text=$(cat <<-END
#     line1
#     line2
#     line3
#     END
#     )
#     GOOD: echo "$text" | fs::write /tmp/hi
#     BAD: echo $text | fs::write /tmp/hi
#
fs::write() {
  local path=$1
  local is_append_mode=false
  local text=$(</dev/stdin)

  # @TODO
  # fs::write -a /tmp/path
  if [ "$path" = "-a" ]; then
    path=$2
    is_append_mode=true
  fi

  if [ "$2" = "true" ]; then
    is_append_mode=true
  fi

  if [ -z "$path" ] || [ -z "$text" ]; then
    log::error "[$(timestamp)][fs::write] path and text is required"
    exit 1
  fi

  # if [ ! -f $path ]; then
  #   log::error "[$(timestamp)][fs::write] path $path not found"
  #   exit 1
  # fi

  # no permission
  # try to use sudo/root
  if [ ! -w $path ]; then
    if [ "$is_append_mode" = "true" ]; then
      sudo tee -a $path >>/dev/null <<EOF
${text}
EOF
    else
      sudo tee $path >>/dev/null <<EOF
${text}
EOF
    fi
    return
  fi

  if [ "$is_append_mode" = "true" ]; then
    echo "$text" >>$path
  else
    echo "$text" >$path
  fi
  #     tee -a $path >> /dev/null <<EOF
  # ${text}
  # EOF
}

fs::read() {
  local path=$1

  if [ -z "$path" ]; then
    log::error "[$(timestamp)][fs::read] path and text is required"
    exit 1
  fi

  if [ ! -f $path ]; then
    log::error "[$(timestamp)][fs::read] path $path not found"
    exit 1
  fi

  if [ ! -r $path ]; then
    log::error "[$(timestamp)][fs::read] path $path permission denied"
    exit 1
  fi

  cat $path
}

fs::append() {
  local path=$1
  local is_append_mode=true
  #
  fs::write $path $is_append_mode
}

fs::remove_empty_line() {
  local file_path=$1
  if [ -z "$file_path" ]; then
    log::error "[$(timestamp)][fs::remove_empty_line] file_path is required"
    exit 1
  fi

  # remove empty line
  #   reference: https://stackoverflow.com/questions/10347653/awk-remove-blank-lines
  awk NF $file_path >$file_path
}

fs::remove_line_has_str() {
  local file_path=$1
  local match_str=$2

  if [ -z "$file_path" ] || [ -z "$match_str" ]; then
    log::error "[$(timestamp)][fs::remove_line_has_str] file_path and match_str is required"
    exit 1
  fi

  sed -i -e "s%.*${match_str}.*%%g" $file_path
}

export -f fs::write
export -f fs::read

export -f fs::append

export -f fs::remove_line_has_str
export -f fs::remove_empty_line
